package org.ekingstar.qd.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.ekingstar.qd.domain.Catalog;
import org.ekingstar.qd.service.CCatalogService;
import org.ekingstar.utils.SysArgUtil;

import com.ekingstar.framework.domain.Function;
import com.ekingstar.framework.security.UserUtil;

public class CCatalogServiceImpl implements CCatalogService {
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	/**
	 * @descripte 保存主题分类信息，保存成功返回1，保存失败返回-1 
	 * @param strName      类别名称
	 * @param strParentId  父类别ID号
	 * @param nOrderNo     排序号
	 * @param strDescript  描述
	 * @return int
	 */
	public int addCategory(String strName, String strParentId, int orderNo,
			String strDescript) {
		// TODO Auto-generated method stub
		int retInt = -1;
		try{
			Catalog catalog = new Catalog();
			catalog.setCatalogName(strName);
			if(strParentId!=null && !"".equals(strParentId.toString().trim())){	
				Catalog parentCatalog = this.getCatalog(strParentId.toString().trim());
				catalog.setParentCatalog(parentCatalog);	
			}else{
				catalog.setParentCatalog(null);				
			}
					
			catalog.setOrderid(orderNo);
			catalog.setDescript(strDescript);
			catalog.setBmId(null);
			
			Function function = this.addFunction(strName, strParentId, orderNo);
			if(function!=null && function.getId()!=null){
				catalog.setFunctionId(function.getId().toString().trim());
				this.hibernateTemplate.save(catalog);
				retInt = 1;
			}else{
				retInt = -1;
			}
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1;
		}
		return retInt;
	}
	
	
	/**
	 * @descripte 保存主题分类菜单信息 
	 * @param strName
	 * @param strParentId
	 * @param orderNo
	 * @return Function
	 */
	private Function addFunction(String strName, String strParentId, int orderNo){
		Function function = new Function();
		try{			
			function.setAddDate(new Date());
			if(UserUtil.getCurrentUser()!=null && UserUtil.getCurrentUser().getName()!=null){
				function.setAdderId(UserUtil.getCurrentUser().getName());
			}else{
				function.setAdderId(null);
			}
			
			function.setName(strName);
			function.setAddresss(null);
			function.setFunctionType(new Integer(1));
			function.setLeaf(false);
			function.setShow(true);
			function.setFilter(true);
			function.setOrderNum(Float.parseFloat(Integer.toString(orderNo)));			
			function.setFunctionCode(Integer.toString(orderNo));
			
			if(strParentId!=null && !"".equals(strParentId)){				
				Catalog parentCatalog = this.getCatalog(strParentId);
				if(parentCatalog!=null && parentCatalog.getCatalogId()!=null && !"".equals(parentCatalog.getCatalogId().toString().trim())){
					String pFunctionId = parentCatalog.getFunctionId();	
					Function pFunction = null;
					if(pFunctionId!=null && !"".equals(pFunctionId.toString().trim())){
						pFunction = this.getFunction(pFunctionId);	
						if(pFunction==null || pFunction.getId()==null || "".equals(pFunction.getId().toString().trim())){
							pFunction = reBuildFunction(parentCatalog);
							if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
								parentCatalog.setFunctionId(pFunction.getId().toString().trim());
								this.hibernateTemplate.saveOrUpdate(parentCatalog);
							}
						}
					}else{
						pFunction = reBuildFunction(parentCatalog);	
						if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
							parentCatalog.setFunctionId(pFunction.getId().toString().trim());
							this.hibernateTemplate.saveOrUpdate(parentCatalog);
						}
					}					
					function.setParent(pFunction);					
				}else{
					Function pFunction = new Function();
					pFunction.setId(SysArgUtil.functionId);
					function.setParent(pFunction);
				}				
			}else{				
				Function pFunction = new Function();
				pFunction.setId(SysArgUtil.functionId);
				function.setParent(pFunction);
			}
						
			this.hibernateTemplate.saveOrUpdate(function);		
		}catch(Exception e){
			e.printStackTrace();
			function = null;			
		}
		return function;
	}
	
	/**
	 * @descript 重新构建菜单
	 * @param catalog
	 * @return Function
	 */
	private Function reBuildFunction(Catalog catalog){			
		Function function = new Function();
		try{
			function.setAddDate(new Date());
			if(UserUtil.getCurrentUser()!=null && UserUtil.getCurrentUser().getName()!=null){
				function.setAdderId(UserUtil.getCurrentUser().getName());
			}else{
				function.setAdderId(null);
			}
			
			function.setName(catalog.getCatalogName());
			function.setAddresss(null);
			function.setFunctionType(new Integer(1));
			function.setLeaf(false);
			function.setShow(true);
			function.setFilter(true);
			function.setOrderNum(Float.parseFloat(Long.toString(catalog.getOrderid())));			
			function.setFunctionCode(Long.toString(catalog.getOrderid()));
			
			Function pFunction = null;
			if(catalog.getParentCatalog()!=null && catalog.getParentCatalog().getCatalogId()!=null && !"".equals(catalog.getParentCatalog().getCatalogId().toString().trim())){
				String pFunctionId = catalog.getParentCatalog().getFunctionId();				
				if(pFunctionId!=null && !"".equals(pFunctionId.toString().trim())){
					pFunction = this.getFunction(pFunctionId);	
					if(pFunction==null || pFunction.getId()==null || "".equals(pFunction.getId().toString().trim())){
						pFunction = reBuildFunction(catalog.getParentCatalog());
						if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
							catalog.getParentCatalog().setFunctionId(pFunction.getId().toString().trim());
							this.hibernateTemplate.saveOrUpdate(catalog.getParentCatalog());
						}
					}
				}else{
					pFunction = reBuildFunction(catalog.getParentCatalog());
					if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
						catalog.getParentCatalog().setFunctionId(pFunction.getId().toString().trim());
						this.hibernateTemplate.saveOrUpdate(catalog.getParentCatalog());
					}
				}				
			}else{
				pFunction = new Function();
				pFunction.setId(SysArgUtil.functionId);
			}	
			
			function.setParent(pFunction);
			this.hibernateTemplate.saveOrUpdate(function);			
		}catch(Exception e){
			e.printStackTrace();
			function = null;
		}
		return function;
	}
	
	
	private Function getFunction(String functionId){
		Function function = null;
		try{
			if(functionId!=null && !"".equals(functionId.toString().trim())){
				function = (Function)hibernateTemplate.get(Function.class, functionId.toString().trim());
			}
		}catch(Exception e){
			e.printStackTrace();
			function = null;
		}
		return function;
	}

	/**
	 * @descripte 根据主题分类Id号，删除相应主题分类信息，同时需要删除该主题分类下的所有子分类及其相应的主题，以及主题相关的配置和授权信息。如果删除成功返回1，否则返回-1 
	 * @param strId        主题分类ID号
	 * @return int
	 */
	public int delCategory(String strId) {
		// TODO Auto-generated method stub
		int retInt = -1;
		try{
			if(strId!=null && !"".equals(strId.toString().trim())){
				Catalog catalog = (Catalog)hibernateTemplate.get(Catalog.class, strId);
				if(delFunction(catalog)>0){
					if(catalog!=null && catalog.getCatalogId()!=null && !"".equals(catalog.getCatalogId().toString().trim())){					
						//删除分类
						String delCatalog = "delete from t_qd_catalog where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id)";
						//删除主题
						String delDomain = "delete from t_qd_domain where id in (select id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除主题和表关系
						String delRelation = "delete from t_qd_domain_dest where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除表关系(主题表达式)
						String delFormula = "delete from t_qd_formula where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除主题查询字段
						String delSimplemeasu = "delete from t_qd_simplemeasu where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除主题过滤条件
						String delWhereClause = "delete from t_qd_where_clause where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除查询字段
						String delComparecond =  "delete from t_qd_comparecond where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除历史查询条件
						String delHiscon =  "delete from t_qd_hiscon where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id))";
						//删除发布查询字段
						String delDelopeComparecond = " delete from t_deploy_qd_comparecond where comparecond_id in (select id from t_qd_comparecond where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id)))";					
						//删除发布主题查询字段
						String delDelopeSimplemeasu = " delete from t_deploy_qd_simplemeasu where simplemeasu_id in (select id from t_qd_simplemeasu where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id)))";
						//删除发布删除主题过滤条件
						String delDelopeWhereClause = " delete from t_deploy_qd_where_clause where where_clause_id in (select id from t_qd_where_clause where domainid in (select id as id from t_qd_domain where catalog_id in (SELECT catalog_id FROM t_qd_catalog START WITH catalog_id ='"+strId+"' CONNECT BY PRIOR catalog_id = parent_id)))";
						String[] sqls = new String[]{delHiscon,delDelopeWhereClause,delDelopeSimplemeasu,delDelopeComparecond,delWhereClause,delSimplemeasu,delComparecond,delFormula,delRelation,delDomain,delCatalog};
						jdbcTemplate.batchUpdate(sqls);
						retInt = 1;
					}
				}				
			}
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1;
		}
		
		return retInt;
	}
	
	
	private int delFunction(Catalog catalog){
		int retInt = -1;
		try{
			if(catalog!=null && catalog.getFunctionId()!=null && !"".equals(catalog.getFunctionId().toString().trim())){				
				//删除functionRrole
				String delFunctionRole =" delete from t_role_function where function_id in (select distinct id from t_function start with id='"+catalog.getFunctionId().toString().trim()+"' connect by prior  id = parent_id )";
				//删除function
				String delFunction = "  delete from t_function where id in (select distinct id from t_function start with id='"+catalog.getFunctionId().toString().trim()+"' connect by prior id = parent_id )";
				String[] sqls = new String[]{delFunctionRole,delFunction};
				jdbcTemplate.batchUpdate(sqls);
				retInt = 1;
			}
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1;
		}
		return retInt ;
	}

	/**
	 * @descripte 根据主题分类ID号，获取相应的主题分类信息 
	 * @param strId 主题分类ID号
	 * @return Catalog
	 */
	public Catalog getCatalog(String strId) {
		// TODO Auto-generated method stub
		if(strId!=null && !"".equals(strId.toString().trim())){
			return (Catalog)hibernateTemplate.get(Catalog.class, strId);
		}else{
			return null;
		}
	}

	//返回所有主题类别信息
	@SuppressWarnings("unchecked")
	public List<Catalog> getCategoryList() {
		// TODO Auto-generated method stub
		return  hibernateTemplate.find(" from Catalog order by orderid ");
		
	}
	
	
	/**
	 * @descripte 根据父主题分类ID号，获取相应的子主题分类信息 
	 * @param strPId 主题父分类ID号
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List<Catalog> getCategoryList(String strPid) {
		// TODO Auto-generated method stub
		if(strPid!=null && !"".equals(strPid.toString().trim())){
			return  hibernateTemplate.find(" from Catalog where  parentCatalog.catalogId='"+strPid+"' order by orderid ");
		}else{
			return  hibernateTemplate.find(" from Catalog where  parentCatalog.catalogId is null order by orderid ");
		}
		
	}


	/**
	 * @descripte 根据主题分类ID号修改主题分类信息，修改成功返回1，否则返回-1 
	 * @param strId        主题分类ID号
	 * @param strName      类别名称
	 * @param nOrderNo     排序号
	 * @param strDescript  描述
	 * @return int
	 */
	public int updateCategory(String strId, String strName, int orderNo, String strDescript) {
		// TODO Auto-generated method stub
		int retInt = -1;
		try{
			Function function  = updateFunction(strId, strName, orderNo);			
			if(strId!=null && !"".equals(strId) && function!=null && function.getId()!=null && !"".equals(function.getId().toString().trim())){
				Catalog catalog = (Catalog)hibernateTemplate.get(Catalog.class, strId);
				catalog.setCatalogName(strName);
				catalog.setOrderid(orderNo);
				catalog.setDescript(strDescript);
				catalog.setFunctionId(function.getId().toString().trim());
				hibernateTemplate.saveOrUpdate(catalog);
				retInt = 1;			
			}					
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1 ;
		}
		
		return retInt;
	}
	
	private Function updateFunction(String strId, String strName, int orderNo){		
		Function function = null;
		try{
			if(strId!=null && !"".equals(strId)){
				Catalog catalog = (Catalog)hibernateTemplate.get(Catalog.class, strId);
				if(catalog!=null && catalog.getCatalogId()!=null && !"".equals(catalog.getCatalogId().toString().trim())){					
					if(catalog.getFunctionId()!=null && !"".equals(catalog.getFunctionId().toString().trim())){
						function =(Function)hibernateTemplate.get(Function.class, catalog.getFunctionId());
						if(function==null || function.getId()==null || "".equals(function.getId().toString().trim())){
							function =this.reBuildFunction(catalog);
						}
					}else{
						function =this.reBuildFunction(catalog);
					}					
					function.setName(strName);
					function.setOrderNum(Float.parseFloat(Integer.toString(orderNo)));			
					function.setFunctionCode(Integer.toString(orderNo));
					hibernateTemplate.saveOrUpdate(function);					
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			function = null;
		}
		return function ;		
	}
	
	
	
	/**
	 * @descripte 校验数据的唯一性 
	 * @param strId 校验类别ID
	 * @param nMode=1 -- 主题分类
	 *     strBelongId  --父节点id号
	 *     strDest      --主题分类名
	 *     
	 * @param nMode=2 -- 主题信息
	 *     strBelongId  --主题分类ID号
	 *     strDest      --主题名     
	 * 
	 * @param nMode=3 -- 查询字段
	 *     strBelongId  --主题ID号
	 *     strDest      --查询字段名称 
	 *     
	 * @param nMode=4 -- 发布字段
	 *     strBelongId  --主题ID号
	 *     strDest      --发布字段名称
	 *     
	 * @param nMode=5 -- 功能
	 *     strBelongId  --父节点id号
	 *     strDest      --功能号
	 * 
	 * @param nMode=6 -- 页面
	 *     strBelongId  --父节点id号
	 *     strDest      --页面编号
	 *     
	 * @return int  -1 已存在  1 不存在
	 */
	public int UniqueCheck(String strDest, String strBelongId, int nMode){
		int retInt = -1;
		try{
			String strSql = null;
			String hql = "";
            if (nMode == 1){
                if (strBelongId == null || strBelongId.toString().trim().length() == 0)                	
                    strSql = "select count(1) row_num from t_qd_catalog where parent_id is null and catalog_name='" + strDest.toString().trim() + "'";
                else
                    strSql = "select count(1) row_num from t_qd_catalog where parent_id ='" + strBelongId.toString().trim() + "' and catalog_name='" + strDest.toString().trim() + "'";               
            }
            else if (nMode == 2)
            {
                if (strBelongId == null || strBelongId.toString().trim().length()== 0){
                    retInt = -1;
                }else{
                    strSql = "select count(1) row_num from t_qd_domain where catalog_id ='" + strBelongId.toString().trim() + "' and name='" + strDest.toString().trim() + "'";
                }                
            }
            else if (nMode == 3)
            {
            	 if (strBelongId == null || strBelongId.toString().trim().length()== 0){
                     retInt = -1;
                 }else{
                    strSql = "select count(1) row_num from t_qd_comparecond where domainid ='" + strBelongId.toString().trim()  + "' and name='" + strDest.toString().trim()+ "'";
                 }
            }
            else if (nMode == 4)
            {
            	if (strBelongId == null || strBelongId.toString().trim().length()== 0){
                    retInt = -1;
                }else{
                    strSql = "select count(1) row_num from t_qd_simplemeasu where domainid ='" + strBelongId.toString().trim()  + "' and name='" + strDest.toString().trim()+ "'";
                }
            }
            else if (nMode == 5)
            {
            	if (strBelongId == null || strBelongId.toString().trim().length() == 0)
                    strSql = "select count(1) row_num from t_qd_function where parentid is null and no='" +  strDest.toString().trim() + "'";
                else
                    strSql = "select count(1) row_num from t_qd_function where parentid ='" + strBelongId.toString().trim() + "' and no='" +  strDest.toString().trim() + "'";
            }
            else if (nMode == 6)
            {
            	if (strBelongId == null || strBelongId.toString().trim().length() == 0)
                    strSql = "select count(1) row_num from t_qd_page where parentid is null and no='" + strDest.toString().trim() + "'";
                else
                    strSql = "select count(1) row_num from t_qd_page where parentid ='" + strBelongId.toString().trim() + "' and no='" + strDest.toString().trim() + "'";                
            }
            
            if(strSql!=null && strSql.toString().trim().length()>0){
            	List retList = this.jdbcTemplate.queryForList(strSql);
            	if(retList!=null && retList.size()>0){
            		ListOrderedMap lom = (ListOrderedMap)retList.get(0);	
            		if(Integer.parseInt(lom.get(lom.get(0)).toString())>0){
            			retInt = -1;
            		}else{
            			retInt = 1;
            		}
            	}
            }
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1;
		}
		
		return retInt ;		
	}
	
	
	
	/**
	 * @descript 特殊字符转换
	 * @转换字符包括：
	 *     &、%、'、_等     
	 */
	private String convertSymbol(String convertStr){
		int retint = 0;
		if(convertStr!=null && !"".equals(convertStr.toString().trim())){
			if(convertStr.indexOf("\\")!=-1){
				retint = 1;
			}
			
			//'符号转换
			if(convertStr.indexOf("'")!=-1){
				String  convertStrTemp = "";
				String  covertStrs = convertStr+"'end";
				String[] temp = covertStrs.split("'");
				
				for(int i=0;i<temp.length-1;i++){					
					if(i==0 && (convertStrTemp==null || "".equals(convertStrTemp.toString().trim())) ){
						convertStrTemp = temp[i];
					}else{
						convertStrTemp += "''"+temp[i];
					}
				}
				convertStr =  convertStrTemp;
			}
			
			//&符号转换
			if(convertStr.indexOf("&")!=-1){
				if(retint <1 ){
					retint = -1;
				}
				String  convertStrTemp = "";
				String  covertStrs = convertStr+"&end";
				String[] temp = covertStrs.split("&");
				
				for(int i=0;i<temp.length-1;i++){					
					if(i==0 && (convertStrTemp==null || "".equals(convertStrTemp.toString().trim())) ){
						convertStrTemp = "'"+temp[i]+"'";
					}else{
						convertStrTemp += "||'"+temp[i]+"'";
					}
				}
				convertStr = convertStrTemp;
			}
			
			//%符号转换
			if(convertStr.indexOf("%")!=-1){
				if(retint <1 ){
					retint = -1;
				}
				String  convertStrTemp = "";
				String  covertStrs = convertStr+"%end";
				String[] temp = covertStrs.split("%");
				
				for(int i=0;i<temp.length-1;i++){					
					if(i==0 && (convertStrTemp==null || "".equals(convertStrTemp.toString().trim())) ){
						convertStrTemp = temp[i];
					}else{
						convertStrTemp += "\\%'"+temp[i]+"'";
					}
				}
				convertStr = convertStrTemp;
			}
			
			//_符号转换
			if(convertStr.indexOf("_")!=-1){
				if(retint <1 ){
					retint = -1;
				}
				String  convertStrTemp = "";
				String  covertStrs = convertStr+"_end";
				String[] temp = covertStrs.split("_");
				
				for(int i=0;i<temp.length-1;i++){					
					if(i==0 && (convertStrTemp==null || "".equals(convertStrTemp.toString().trim())) ){
						convertStrTemp = temp[i];
					}else{
						convertStrTemp += "\\_'"+temp[i]+"'";
					}
				}
				convertStr = convertStrTemp;
			}
			
			if(retint<0){
				convertStr += " escape '\\' ";
			}
		}		
		return convertStr;		
	}
	
}
